package ecommerce.action;

import java.util.*;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import ecommerce.model.Tag;
import ecommerce.dao.TagDAOImpl;
import ecommerce.model.User;
import ecommerce.dao.UserDAOImpl;
import ecommerce.dao.UserTagDAOImpl;

public class StatisticsAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	public List<User> users;
	public ArrayList<ArrayList<String>> tagsDistribution;
	public int maxTagPage;
	
	public String collectUserStatistics() {
		users = new UserDAOImpl().getMembers();
		return SUCCESS;
	}
	
	public String adminPage(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("currentTagPage", 1);
		maxTagPage = (int)Math.ceil((((double)new UserTagDAOImpl().getTotalTags()) / 20));
		return SUCCESS;
	}
	
	public String collectTagDistribution() {
		maxTagPage = (int)Math.ceil((((double)new UserTagDAOImpl().getTotalTags()) / 20));
		Map<String, Object> session = ActionContext.getContext().getSession();
		ArrayList<ArrayList<Integer>> tagsFrequency = new UserTagDAOImpl().getUserTagSumFrequency((Integer.parseInt(session.get("currentTagPage").toString())-1) * 20);
		tagsDistribution = new ArrayList<ArrayList<String>>();
		for(int i = 0; i < tagsFrequency.size(); i++)
		{
			Tag t = new TagDAOImpl().getTagById(tagsFrequency.get(i).get(0));
			ArrayList<String> tempList = new ArrayList<String>();
			tempList.add(t.getTagDescription());
			tempList.add(Integer.toString(tagsFrequency.get(i).get(1)));
			tagsDistribution.add(tempList);
		}
		return SUCCESS;
	}
	
	public String setTagPageNumber(){
		try
		{
			Map<String, Object> params = ActionContext.getContext().getParameters();
			Map<String, Object> session = ActionContext.getContext().getSession();
		    session.put("currentTagPage", Integer.parseInt(((String[])params.get("page"))[0]));
		}
		catch(Exception e)
		{
			addFieldError("keyword", "Error on retrieving tag distribution data");
		}
		return SUCCESS;
	}
	
	public void setTagsDistribution(ArrayList<ArrayList<String>> tagsDistribution) {
		this.tagsDistribution = tagsDistribution;
	}
	
	public void setUsers(List<User> users) {
		this.users = users;
	}
	
	public List<User> getUsers() {
		return users;
	}
	
	public ArrayList<ArrayList<String>> getTagsDistribution() {
		return tagsDistribution;
	}
	
	public void setMaxTagPage(int maxTagPage) {
		this.maxTagPage = maxTagPage;
	}
	
	public int getMaxTagPage() {
		return maxTagPage;
	}
}
